package org.jeecg.modules.wlhy.company.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.paycenter.channel.bankdocking.dto.RespPacket;
import org.jeecg.modules.paycenter.channel.bankdocking.utils.BankUtils;
import org.jeecg.modules.third.dongjiang.tax.system.dto.ApiBaseResDTO;
import org.jeecg.modules.wlhy.bill.entity.HyDriverBill;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.entity.HyCompanyDTO;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.DataMaskingUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description: hy_company
 * @Author: jeecg-boot
 * @Date:   2021-01-17
 * @Version: V1.0
 */
@Api(tags="hy_company")
@RestController
@RequestMapping("/company/hyCompany")
@Slf4j
public class HyCompanyController extends JeecgController<HyCompany, IHyCompanyService> {
	@Autowired
	private IHyCompanyService hyCompanyService;

	@Autowired private BankUtils bankUtils;

	@Resource
	private IHySettingService settingService;

	 @GetMapping(value = "/getAccountInfo")
	 public Result<?> getAccountBookInfo(@RequestParam(name="id" , defaultValue = "") String  id) throws Exception {
	 	if(StringUtils.isEmpty(id)){
			return Result.error("数据不存在");
		}

		 HyConfig config = HyConfigUtils.getConfig();
		 if (!config.getNhbankIzUse()) {
			 return Result.error("未开通服务！");
		 }

		 HyCompany hyCompany = hyCompanyService.getById(id);
		 if(hyCompany == null){
			 return Result.error("数据不存在");
		 }
		 String accNo = hyCompany.getAccNo();
		 String prov = hyCompany.getProv();
		 if(StringUtils.isEmpty(accNo)){
			 return Result.error("银行账户信息错误,请检查账户是否配置正确");
		 }
		 if(StringUtils.isEmpty(prov)){
			 return Result.error("银行省市代码不能为空");
		 }
		 try {
			 RespPacket accountBalance = bankUtils.getAccountBalance(hyCompany.getAccNo(), hyCompany.getProv());
			 if (accountBalance.isSuccess()) {
				 return Result.OK(accountBalance.getAcc());
			 } else {
				 return Result.error(accountBalance.getRespInfo());
			 }
		 } catch (Exception e) {
			 return Result.error("查询失败," + e.getMessage());
		 }
	 }

	/**
	 * test
	 * @param pageNo
	 * @return
	 */
	@GetMapping(value = "/getCompanyAndConfig")
	public Result<?> getCompanyAndConfig(  @RequestParam(name="pageNo") Integer pageNo )  {
	 	if(pageNo==2){
			return Result.OK(
					hyCompanyService.getCompanyAndConfig(
							(HyCompanyDTO) new HyCompanyDTO().setTaxUploadType(1)
					)
			);
		}else{
			return Result.OK(
					hyCompanyService.getCompanyAndConfig(
							new HyCompanyDTO().setTaxTjUploadStatus("1")
					)
			);
		}

	}

	 //上传分公司企业数据
	 @PostMapping(value = "/tjTaxUpload")
	 public Result<?> tjTaxUpload(@RequestBody HyCompanyConfig hyCompany) {
		 ApiBaseResDTO result  =  hyCompanyService.tjTaxUpload(hyCompany.getCompanyId());
		 int code =  StringUtils.isNotEmpty(result.getCode())? Integer.parseInt(result.getCode()) : 0;
		 if( code >= 100 && code < 200 ){
			 return Result.OK("上报成功");
		 }
		 return Result.error("上报失败！" + result.getDesc());
	 }

	/**
	 * 分页列表查询
	 *
	 * @param hyCompany
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="hy_company-分页列表查询", notes="hy_company-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyCompany hyCompany,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HyCompany> queryWrapper = QueryGenerator.initQueryWrapper(hyCompany, req.getParameterMap());
		queryWrapper.eq("del_flag", 0);
		Page<HyCompany> page = new Page<HyCompany>(pageNo, pageSize);
		IPage<HyCompany> pageList = hyCompanyService.page(page, queryWrapper);

		//如果开启系统脱敏
		String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
		if("1".equals(dataMaskingFlag)) {
			for (HyCompany dto : pageList.getRecords()) {
				dto.setAccNo(DataMaskingUtil.bankNumberMasking(dto.getAccNo()));
				dto.setFddbrsfzjhm(DataMaskingUtil.idcardMasking(dto.getFddbrsfzjhm()));
				dto.setCwfzrsfzjhm(DataMaskingUtil.idcardMasking(dto.getCwfzrsfzjhm()));
				dto.setBsrsfzjhm(DataMaskingUtil.idcardMasking(dto.getBsrsfzjhm()));
			}
		}

		return Result.OK(pageList);
	}

//	 @GetMapping(value = "/getgasinfo")
//	 public Result<?> getgasinfo() {
//		 LoginUser loginUser = UserUtil.getLoginUser();
//		 String uType = loginUser.getUType();
//		 if(!"2".equals(uType) && !"3".equals(uType)){
//		 	return Result.error("货主信息错误");
//		 }
//
//		 HyCompany selCompany = userUtil.getSelCompany("");
//		 //izNucarf
//		 return Result.OK(selCompany.getIzNucarf());
//	 }

	/**
	 *   添加
	 *
	 * @param hyCompany
	 * @return
	 */
	@AutoLog(value = "hy_company-添加")
	@ApiOperation(value="hy_company-添加", notes="hy_company-添加")
	@PostMapping(value = "/add")
	@RequiresPermissions("sys:company:add")
	public Result<?> add(@RequestBody HyCompany hyCompany) {
		hyCompany.setUploadStatus("0");
		hyCompany.setMonitorsState("0");
		hyCompanyService.save(hyCompany);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hyCompany
	 * @return
	 */
	@AutoLog(value = "hy_company-编辑")
	@ApiOperation(value="hy_company-编辑", notes="hy_company-编辑")
	@PutMapping(value = "/edit")
	@RequiresPermissions("sys:company:edit")
	@CacheEvict(value = CacheConstant.SYS_DICT_TABLE_CACHE ,key = "'SimpleKey [hy_company,company_name,id,' + #hyCompany.id + ']'")
	public Result<?> edit(@RequestBody HyCompany hyCompany) {
		hyCompanyService.updateById(hyCompany);
		return Result.OK("编辑成功!");
	}

//	/**
//	 *   通过id删除
//	 *
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "hy_company-通过id删除")
//	@ApiOperation(value="hy_company-通过id删除", notes="hy_company-通过id删除")
//	@DeleteMapping(value = "/delete")
//	@RequiresPermissions("sys:company:delete")
//	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//		hyCompanyService.removeById(id);
//		return Result.OK("删除成功!");
//	}
//
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "hy_company-批量删除")
//	@ApiOperation(value="hy_company-批量删除", notes="hy_company-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	@RequiresPermissions("sys:company:deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyCompanyService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="hy_company-通过id查询", notes="hy_company-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HyCompany hyCompany = hyCompanyService.getById(id);
		if(hyCompany==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hyCompany);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hyCompany
    */
    @RequestMapping(value = "/exportXls")
	@RequiresPermissions("sys:company:exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HyCompany hyCompany) {
        return super.exportXls(request, hyCompany, HyCompany.class, "hy_company");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@RequiresPermissions("sys:company:importExcel")
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HyCompany.class);
    }

	@GetMapping(value = "/all")
	public Result<?> getAll(HyCompany hyCompany,HttpServletRequest req) {
		QueryWrapper<HyCompany> queryWrapper = QueryGenerator.initQueryWrapper(hyCompany, req.getParameterMap());
		queryWrapper.eq("iz_used", "1");
		List <HyCompany> list = hyCompanyService.list(queryWrapper);
		return Result.OK(list);
	}

}
